package com.ncmmall.mall.controller.business.setting;

import com.ncmmall.application.business.cancelcarse.CancelCauseApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.setting.CancelCause;
import com.ncmmall.domain.business.setting.QCancelCause;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 取消原因管理
 *
 * @author likaikai
 * @date 2019-07-11 11:18
 */
@Controller
@RequestMapping("/mall/cancelcause")
public class CancelCauseController {

    private Logger logger = LoggerFactory.getLogger(CancelCauseController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private OperationLogApplication logApplication;

    @Autowired
    private CancelCauseApplication cancelCauseApplication;

    /**
     * 取消原因列表
     *
     * @param model
     * @param pageParams
     * @param param
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, CancelCause params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());

        Map<String, Object> map = new HashMap<>(2);
        String sql = buildSql("select * from mall_cancel_couse where 1 = 1", map, params);

        QueryPage<CancelCause> page = queryChannelService.queryPageEntity(sql, pageRequest.setParams(map), CancelCause.class);

        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/cancelcause/list";
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param map
     * @param params
     * @return
     */
    private String buildSql(String sql, Map<String, Object> map, CancelCause params) {

        if (params.getStatus() > 0) {
            sql += " and status = :status";
            map.put("status", params.getStatus());
        }

        if(!Strings.isNullOrEmpty(params.getCouse())) {
            sql += " and couse like :couse ";
            map.put("couse", "%" + params.getCouse() + "%");
        }

        sql += " order by sorz desc";

        return sql;
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {
        model.addAttribute("cancelCause", new CancelCause()).addAttribute("_method", "post");
        return "mall/cancelcause/form";
    }

    /**
     * 创建取消原因
     *
     * @param requestWith
     * @param cancelCause
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, CancelCause cancelCause) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            cancelCauseApplication.create(cancelCause);

            logApplication.eventOfSystem(Securitys.currentUser(), "添加取消原因", Securitys.getIp(request));

            return ImmutableMap.of("status", true, "message", "创建成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("取消原因创建异常", e);
            return ImmutableMap.of("status", false, "message", "创建异常");

        }
    }

    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {
        model.addAttribute("cancelCause", queryChannelService.findOne(QCancelCause.cancelCause.id.eq(id), CancelCause.class)).addAttribute("_method", "PUT");

        return "mall/cancelcause/form";
    }

    /**
     * 编辑取消原因
     *
     * @param requestWith
     * @param cancelCause
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, CancelCause cancelCause) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            cancelCauseApplication.modify(cancelCause);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑取消原因渠道", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "编辑成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("取消原因编辑异常", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");

        }
    }

    /**
     * 下架取消原因
     *
     * @param requestWith
     * @param cancelCause
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, CancelCause cancelCause) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            cancelCauseApplication.disable(queryChannelService.findOne(QCancelCause.cancelCause.id.eq(cancelCause.getId()), CancelCause.class));
            logApplication.eventOfSystem(Securitys.currentUser(), "下架取消原因渠道", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (Exception e) {

            logger.error("取消原因下架异常", e);
            return ImmutableMap.of("status", false, "message", "下架异常");

        }
    }


    /**
     * 上架取消原因
     *
     * @param requestWith
     * @param cancelCause
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, CancelCause cancelCause) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            cancelCauseApplication.enabled(queryChannelService.findOne(QCancelCause.cancelCause.id.eq(cancelCause.getId()), CancelCause.class));
            logApplication.eventOfSystem(Securitys.currentUser(), "上架取消原因渠道", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (Exception e) {

            logger.error("取消原因上架异常", e);
            return ImmutableMap.of("status", false, "message", "上架异常");

        }
    }


    /**
     * 删除取消原因
     *
     * @param requestWith
     * @param cancelCause
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, CancelCause cancelCause) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            cancelCauseApplication.remove(queryChannelService.findOne(QCancelCause.cancelCause.id.eq(cancelCause.getId()), CancelCause.class));
            logApplication.eventOfSystem(Securitys.currentUser(), "删除取消原因渠道", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (Exception e) {

            logger.error("取消原因删除异常", e);
            return ImmutableMap.of("status", false, "message", "删除异常");

        }
    }

}
